package com.game_info.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.game_info.service.GamesService;
import com.game_info.utils.AjaxResult;
import com.game_info.vo.Games;
import com.game_info.vo.gImage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;


/**
 * games表Controller
 *
 * @author ttj
 * @date 2020-04-09
 */
@Controller
@RequestMapping("/games")
public class GamesController {

    @Autowired
    private GamesService gamesService;
    @Autowired
    private HttpServletRequest request;

    ObjectMapper mapper = new ObjectMapper();

    /**
     * 传入空对象会查询所有游戏列表
     * <p>
     * 根据中英文名查询模糊查询游戏
     * 也可加上其他任意字段组合
     */
    @PostMapping("/list.do")
    @ResponseBody
    public AjaxResult list(@RequestBody @RequestParam(required = false) Games games) {
        List<Games> list = gamesService.selectGamesList(games);
        return AjaxResult.put(list, "模糊查询游戏列表方法执行成功", list.size());
    }

    /**
     * 分页查询
     *
     * @param page 当前请求页数
     * @return 结果集
     */
    @GetMapping("/limit.do")
    @ResponseBody
    public AjaxResult limit(Integer page, @RequestParam(value = "limit", required = false) Integer limit) throws IOException {
        if (limit == null) {
            limit = 6;//默认分页数据量6
        }
        //入参小于0的情况.
        if (page <= 0) {
            page = 1;
        }
        Integer maxPage = gamesService.selectListCount() / limit + 1;//总页数
        List<Games> list = gamesService.selectGamesListLimit((page - 1) * limit, limit);
        //循环,获取图片地址
        for (Games ls : list) {
            if (ls.getgImage() != null && ls.getgImage() != "") {
                gImage gImage = mapper.readValue(ls.getgImage(), gImage.class);
                ls.setgImagevo(gImage);
            } else {
                //没有图片情况下,设置默认图片提示
                ls.setgImagevo(new gImage("/dev_resources_folder/game_images/null.jpg"));
            }
        }
        return AjaxResult.put(list, "分页查询方法执行成功", maxPage);
    }

    /**
     * 获取游戏列表总数
     *
     * @return 游戏总条数
     */
    @GetMapping("/listCount.do")
    @ResponseBody
    public int ListCount() {
        return gamesService.selectListCount();
    }

    /**
     * 根据关键词模糊查询全部游戏信息
     *
     * @param keyword
     * @return
     */
    @GetMapping("/selectLikeKeyword.do")
    @ResponseBody
    public List<Games> selectLikeKeyword(String keyword) {
        return gamesService.selectLikeKeyword(keyword);
    }

    /**
     * 根据id查询单条游戏
     *
     * @param gId
     * @return Game
     */
    @GetMapping("/selectOneGame.do")
    @ResponseBody
    public Games selectOneGame(Integer gId) throws IOException {
        Games games = gamesService.selectGamesById(gId);
        if (games.getgImage() != null && games.getgImage() != "") {//判断图片是否为空
            //将数据库中的json字符串转换成json对象
            gImage gImage = mapper.readValue(games.getgImage(), gImage.class);
            //重新赋给对象
            games.setgImagevo(gImage);
        } else {
            games.setgImagevo(new gImage("/dev_resources_folder/game_images/null.jpg"));
        }
        return games;
    }

    /**
     * 多文件上传
     * @param multipartFiles
     * @param gId
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadGimageById.do")
    @ResponseBody
    public AjaxResult uploadGimageById(@RequestParam("file") MultipartFile multipartFiles,@RequestBody @RequestParam("gId")Integer gId) throws IOException {
        //判断集合是否为空
        if(multipartFiles.isEmpty()){
            //结束
            return AjaxResult.put(0,gId,"上传失败,没有选择上传文件",0);
        }
        //获取存取路径
        //request.getServletContext().getRealPath("");//服务器项目路径
        String path="/dev_resources_folder/game_images/"+gId;//虚拟资源路径
        File f = new File(path);
        // 获取文件后缀
        String houzui=multipartFiles.getOriginalFilename().substring(multipartFiles.getOriginalFilename().indexOf("_")+1,multipartFiles.getOriginalFilename().indexOf("_")+2) ;
        System.out.println(houzui);
        String fname=multipartFiles.getOriginalFilename();//文件名
        if (!f.exists()){
            f.mkdirs();//如果不存在,创建文件夹
            // 定义存储路径目录路径+文件名
            File ff=new File(path,fname);
            //上传
            multipartFiles.transferTo(ff);
            return AjaxResult.put(1,gId,"上传成功",0);
        }else {
            // 定义存储路径目录路径+文件名
            File ff=new File(path,fname);
            //上传
            multipartFiles.transferTo(ff);
            return AjaxResult.put(1,gId,"上传成功",0);
        }
    }

    /**
     * 获取图片id编号
     * @param imgName
     * @return
     */
    private String getGImageId(String imgName){
        if (imgName!=null){
            return imgName.substring(imgName.indexOf("_")+1,imgName.indexOf("."));
        }else {
            return "";
        }
    }

    /**
     * 确认应用上传的图片
     * @param gId
     * @return
     */
    @GetMapping("/saveUpdateGImage.do")
    @ResponseBody
    public Integer saveUpdateGImage(Integer gId) throws JsonProcessingException {
        gImage gImage=new gImage();
        List<String> imgNamelist = new ArrayList<>();
        String path = "/dev_resources_folder/game_images/"+gId;//虚拟资源路径
        File file = new File(path);
        File[] files = file.listFiles();//获取当前游戏图片文件夹下的游戏图片
        for (File img:files) {
            imgNamelist.add(img.getName());//将文件名添加进集合
            System.out.println(img.getName());
        }
        for (String imgName:imgNamelist) {
            if (getGImageId(imgName).equals("0")){
                gImage.setUrl0(path+"/"+imgName);
            }else if (getGImageId(imgName).equals("1")){
                gImage.setUrl1(path+"/"+imgName);
            }else if (getGImageId(imgName).equals("2")){
                gImage.setUrl2(path+"/"+imgName);
            }else if (getGImageId(imgName).equals("3")){
                gImage.setUrl3(path+"/"+imgName);
            }else if (getGImageId(imgName).equals("4")){
                gImage.setUrl4(path+"/"+imgName);
            }else if (getGImageId(imgName).equals("5")){
                gImage.setUrl5(path+"/"+imgName);
            }else if (getGImageId(imgName).equals("6")){
                gImage.setUrl6(path+"/"+imgName);
            }else if (getGImageId(imgName).equals("7")){
                gImage.setUrl7(path+"/"+imgName);
            }else if (getGImageId(imgName).equals("8")){
                gImage.setUrl8(path+"/"+imgName);
            }else if (getGImageId(imgName).equals("9")){
                gImage.setUrl9(path+"/"+imgName);
            }else if (getGImageId(imgName).equals("10")){
                gImage.setUrl10(path+"/"+imgName);
            }
        }
        return gamesService.updateGimageById(gImage,gId);
    }



    /**
     * 新增保存游戏
     */
    @PostMapping("/add.do")
    @ResponseBody
    public AjaxResult add(@RequestBody Games games) {
        return AjaxResult.put(gamesService.insertGames(games), "新增游戏方法执行成功");
    }


    /**
     * 修改保存游戏
     */
    @PostMapping("/edit.do")
    @ResponseBody
    public AjaxResult edit(@RequestBody Games games) {
        return AjaxResult.put(gamesService.updateGames(games), "修改游戏方法执行成功");
    }

    /**
     * 根据id删除游戏
     */
    @PostMapping("/remove.do")
    @ResponseBody
    public AjaxResult remove(@RequestBody Integer id) {
        return AjaxResult.put(gamesService.deleteGamesById(id), "根据id删除游戏方法执行成功");
    }
}
